import re

from PageObjectRequests import base_url
from util import http_utils
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g
from util.inform.sendEmail import sendEmail
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from PageObjectRequests.WriteHrInfo import WriteHRInfo
from PageObjectRequests.WriteHrSubinfo import WriteHRSubinfo

# 0a198502c53c11eba90a00163e827061
# HAAJ993HU3OF7JDDH1MX28O90XM80YRY
class WriteHRForm():
    token = ""
    form_btn_loc = (By.LINK_TEXT, '人力资源情况表')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    title_loc = (By.CSS_SELECTOR, 'h2.text-center')

    upload_btn_loc = (By.CSS_SELECTOR, '.uploadAttachment a.btn')
    save_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right #dataEnmanressave')

    # 写代码时方便提示, 基本方法完成后删除
    # driver = driver
    def __init__(self, driver=None):
        self.driver = driver
        self.file_id = 15
        # 人力资源附件大小限制 单位 M
        self.size = 8

    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, doctor=None, md=None, bd=None, coll=0, senior=0, medium=0, primary=0, snengr=0, age30al=0, age40al=0, age50al=0, age51au=0):
        try:
            ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc)
            detail_url = ele.get_attribute("href")
            if not g.all_optimized:
                BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
            BM.get_cookie(driver=self.driver)
            detail_url = detail_url if detail_url.startswith("https://") else \
                base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            res = http_utils.send_get(detail_url, driver=self.driver)
            text = res.get("text")
            token = res.get("token")
            self.token = token

            url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEntHumanres.do"

            data = {
                "struts.token.name": "token",
                "token": token
            }
            #   数据查询模块实现后需要先查询数据，在调用 write_hr_info 、 write_hr_subinfo 方法
            hr_info = WriteHRInfo(driver=self.driver).write_hr_info()
            for hr in hr_info:
                data.update(hr)
            form_data = {"dataEntHumanres.entHrDoctor": str(doctor), "dataEntHumanres.entHrMaster": str(md),
                "dataEntHumanres.entHrBachelor": str(bd), "dataEntHumanres.entHrJunior": str(coll),
                "dataEntHumanres.entHrSenior":str(senior), "dataEntHumanres.entHrMiddle": str(medium),
                "dataEntHumanres.entHrPrimary": str(primary), "dataEntHumanres.entHrMechanic": str(snengr),
                "dataEntHumanres.entHrAge1": str(age30al), "dataEntHumanres.entHrAge2": str(age40al),
                "dataEntHumanres.entHrAge3": str(age50al), "dataEntHumanres.entHrAge4": str(age51au)}
            # hr_subinfo = WriteHRSubinfo(driver=self.driver).write_hr_subinfo()
            data.update(form_data)

            dataEntHumanres_id_pattern = '.*?name="dataEntHumanres.id".value="(.*?)".*?'
            id_res = re.findall(dataEntHumanres_id_pattern, text, re.S)
            data["dataEntHumanres.id"] = "".join(id_res)

            dataEntHumanres_dataId_pattern = '.*?name="dataEntHumanres.dataId".value="(.*?)".*?'
            dataId_res = re.findall(dataEntHumanres_dataId_pattern, text, re.S)
            data["dataEntHumanres.dataId"] = "".join(dataId_res)

            dataEntHumanres_entId_pattern = '.*?name="dataEntHumanres.entId".value="(.*?)".*?'
            entId_res = re.findall(dataEntHumanres_entId_pattern, text, re.S)
            data["dataEntHumanres.entId"] = "".join(entId_res)

            dataEntHumanres_createDate_pattern = '.*?name="dataEntHumanres.createDate".value="(.*?)".*?'
            createDate_res = re.findall(dataEntHumanres_createDate_pattern, text, re.S)
            data["dataEntHumanres.createDate"] = "".join(createDate_res)

            # 若有附件 等待附件拆分
            file_path = BM.get_material_path() + "\\hr.pdf"
            hr_pdf = DbTools.get_pdf_record(co_id=g.co_id, year=g.year, rule_id=self.file_id)
            # 已经上传附件就不在上传了
            if u"点击下载" not in text:
                if g.need_file and hr_pdf and hr_pdf.get("oss_path"):
                    oss_path = hr_pdf.get("oss_path")
                    is_exist = BM.check_file(file_path=file_path, size=self.size)
                    if is_exist is False:
                        oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
                        BM.wait_file(file_path=oss_file)
                        CompressPdf(file_path=oss_file, max_size=self.size).compress()
                        BM.wait_file(file_path=file_path)
                else:
                    file_path = None
            else:
                file_path = None


            # 发送请求时 若有附件则传入附件路径
            result = http_utils.send_post(url, data=data, file_path=file_path, driver=self.driver)
            text = result.get("text")
            message = result.get("message")
            g.logger.info("人力资源情况表上传结果: {}".format(message))
            token = result.get("token")
            self.token = token

            if u"成功" in message:
                return True
            else:
                content = "{}-{}---{}--{}".format(g.entname, g.co_id, "人力资源情况", message)
                a = sendEmail(subject="autoflow", content=content, target="18235693860@163.com")
                a.send_mail()
                return False

        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
